<?php

namespace Apps\AppApi\Method\User;

use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Models\UserAttribute;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\UserBase;
use Apps\Common\Libs\PicUrl;

/**
 * 专家列表
 */
class ExperFollowList extends BaseMethod
{
    public function run()
    {
		/**
		 * 验证用户权限，但不抛错
		 */
		/*$this->verifyUserAuth(false);
    	$user_id = $this->getUserAuth()->userId;*/

    	$user_id = intval($this->getDataItem('user_id', 0));
    	$page = intval($this->getDataItem('page', 1));

		$limit = $this->getConfig()->limit;
		$offset = ($page - 1) * $limit;

		if ($user_id > 0)
		{
			$list = UserBase::query()->columns([
				'IF(f.to_user_id, 1, 0) AS fid',
				'Apps\Common\Models\UserBase.user_id',
				'user_nickname',
				'user_cover',
				'expert_follow_count',
				'f.to_user_id',
				'a.attr_value_json'
			])->leftJoin('Apps\Common\Models\UserFollow', "Apps\\Common\\Models\\UserBase.user_id = f.to_user_id and f.user_id = {$user_id} and f.type = 2", 'f')
				->leftJoin('Apps\Common\Models\UserAttribute', 'a.user_id = Apps\\Common\\Models\\UserBase.user_id and a.attr_type = 103 and a.attr_state = 1', 'a')->where('user_expert = 1 and user_state = 1')->orderBy('fid DESC, expert_follow_count DESC')->limit($limit, $offset)->execute()->toArray();
		}
		else
		{
			$list = UserBase::query()->columns([
				'Apps\Common\Models\UserBase.user_id',
				'user_nickname',
				'user_cover',
				'expert_follow_count',
				'a.attr_value_json'
			])->leftJoin('Apps\Common\Models\UserAttribute', 'a.user_id = Apps\Common\Models\UserBase.user_id and a.attr_type = 103 and a.attr_state = 1', 'a')->where('user_expert = 1 and user_state = 1')->orderBy('expert_follow_count DESC')->limit($limit, $offset)->execute()->toArray();
		}
		foreach ($list as $k => $val) {
			$list[$k]['user_cover'] = PicUrl::ActivityCover($val['user_cover'], $this->getDi());

			// 获取专家的扩展信息
			$info = $val['attr_value_json'] ? json_decode($val['attr_value_json']) : [];
			$list[$k]['experience'] = $info->experience ?: '0'; // 从业经验
			$list[$k]['experttitle'] = $info->experttitle ?: ''; // 擅长领域
			$list[$k]['field'] = $info->field ?: []; // 专家头衔(array)
			$list[$k]['is_follow'] = $val['to_user_id'] ? '1' : '0';
			unset($list[$k]['to_user_id'], $list[$k]['attr_value_json']);
		}
		$this->setResult($list);
    }
}